
import java.awt.image.BufferedImage;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

/**
 * @author huangzd
 * @version 创建时间：2015年5月21日 下午1:58:36
 * @describe
 */
public class QRCodeUtils {

	private static final int BLACK = 0xff000000;
	private static final int WHITE = 0xFFFFFFFF;

	public static BufferedImage getImage(String contents, int width, int height) throws Exception {
		BufferedImage image = encode(contents, BarcodeFormat.QR_CODE, width, height);
		return image;
	}

	/**
	 * @author huangzd
	 * @version 2015年5月21日下午2:01:25
	 * @throws Exception 
	 * @describe 生成QRCode二维码<br>
	 *           在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>
	 *           static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>
	 *           修改为UTF-8，否则中文编译后解析不了<br>
	 */
	private static BufferedImage encode(String contents, BarcodeFormat format, int width, int height) throws Exception {
		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) == true ? BLACK : WHITE);
			}
		}
		return image;
	}
}